package cn.jinbyte.core.utils;

import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.IoUtil;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * Servlet工具类
 *
 * @author jintingying
 * @since 1.0.0
 */
@Slf4j
public class ServletUtils {

    /**
     * 获取请求头信息
     *
     * @param request HttpServletRequest对象
     * @return 包含所有请求头的Map
     */
    public static Map<String, String> getHeaders(HttpServletRequest request) {
        Map<String, String> headers = new HashMap<>();
        Enumeration<String> headerNames = request.getHeaderNames();

        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            headers.put(headerName, request.getHeader(headerName));
        }

        return headers;
    }

    /**
     * 获取响应头信息
     *
     * @param response HttpServletResponse对象
     * @return 响应头信息
     */
    public static Map<String, String> getHeaders(HttpServletResponse  response) {
        Map<String, String> headers = new HashMap<>();
        Collection<String> headerNames = response.getHeaderNames();
        for (String headerName : headerNames) {
            headers.put(headerName, response.getHeader(headerName));
        }
        return headers;
    }


    /**
     * 获取请求的所有参数
     *
     * @param request HttpServletRequest对象
     * @return 包含所有参数的Map
     */
    public static Map<String, String> getParameters(HttpServletRequest request) {
        Map<String, String> params = new HashMap<>();
        Enumeration<String> paramNames = request.getParameterNames();

        while (paramNames.hasMoreElements()) {
            String paramName = paramNames.nextElement();
            params.put(paramName, request.getParameter(paramName));
        }

        return params;
    }

    /**
     * 获取请求体数据
     *
     * @param request HttpServletRequest对象
     * @return 请求体数据
     */
    public static String getBody(ServletRequest request) {
        try (BufferedReader reader = request.getReader()) {
            return IoUtil.read(reader);
        } catch (IOException e) {
            throw new IORuntimeException(e);
        }
    }

    /**
     * 获取客户端IP地址
     *
     * @param request HttpServletRequest对象
     * @return 客户端IP地址
     */
    public static String getClientIP(HttpServletRequest request) {
        String ip = null;

        // X-Forwarded-For：Squid 服务代理
        String ipAddresses = request.getHeader("X-Forwarded-For");
        if (ipAddresses == null || ipAddresses.isEmpty() || "unknown".equalsIgnoreCase(ipAddresses)) {
            // Proxy-Client-IP：apache 服务代理
            ipAddresses = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddresses == null || ipAddresses.isEmpty() || "unknown".equalsIgnoreCase(ipAddresses)) {
            // WL-Proxy-Client-IP：weblogic 服务代理
            ipAddresses = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddresses == null || ipAddresses.isEmpty() || "unknown".equalsIgnoreCase(ipAddresses)) {
            // HTTP_CLIENT_IP：有些代理服务器
            ipAddresses = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ipAddresses == null || ipAddresses.isEmpty() || "unknown".equalsIgnoreCase(ipAddresses)) {
            // X-Real-IP：nginx服务代理
            ipAddresses = request.getHeader("X-Real-IP");
        }

        // 有些网络通过多层代理，那么获取到的ip就会有多个，一般都是通过逗号（,）分割开来，并且第一个ip为客户端的真实IP
        if (ipAddresses != null && !ipAddresses.isEmpty()) {
            ip = ipAddresses.split(",")[0];
        }

        // 还是不能获取到，最后再通过request.getRemoteAddr();获取
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ipAddresses)) {
            ip = request.getRemoteAddr();
        }
        return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
    }


    /**
     * 向客户端输出JSON格式数据
     *
     * @param response HttpServletResponse对象
     * @param json     JSON字符串
     * @throws IOException IO异常
     */
    public static void writeJson(HttpServletResponse response, String json) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        try (PrintWriter writer = response.getWriter()) {
            writer.write(json);
            writer.flush();
        }
    }

    /**
     * 向客户端输出文本数据
     *
     * @param response HttpServletResponse对象
     * @param text     文本内容
     * @throws IOException IO异常
     */
    public static void writeText(HttpServletResponse response, String text) throws IOException {
        response.setContentType("text/plain;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        try (PrintWriter writer = response.getWriter()) {
            writer.write(text);
            writer.flush();
        }
    }

    /**
     * 获取Session中的属性值
     *
     * @param request HttpServletRequest对象
     * @param name    属性名称
     * @param clazz   属性类型
     * @param <T>     泛型类型
     * @return Session中的属性值
     */
    @SuppressWarnings("unchecked")
    public static <T> T getSessionAttribute(HttpServletRequest request, String name, Class<T> clazz) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            Object attribute = session.getAttribute(name);
            if (clazz.isInstance(attribute)) {
                return (T) attribute;
            }
        }
        return null;
    }

    /**
     * 设置Session属性
     *
     * @param request HttpServletRequest对象
     * @param name    属性名称
     * @param value   属性值
     */
    public static void setSessionAttribute(HttpServletRequest request, String name, Object value) {
        HttpSession session = request.getSession(true);
        session.setAttribute(name, value);
    }

    /**
     * 移除Session属性
     *
     * @param request HttpServletRequest对象
     * @param name    属性名称
     */
    public static void removeSessionAttribute(HttpServletRequest request, String name) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.removeAttribute(name);
        }
    }

    /**
     * 判断是否为Ajax请求
     *
     * @param request HttpServletRequest对象
     * @return 是否为Ajax请求
     */
    public static boolean isAjaxRequest(HttpServletRequest request) {
        String requestedWith = request.getHeader("X-Requested-With");
        return "XMLHttpRequest".equals(requestedWith);
    }

    /**
     * 判断是否为POST请求
     *
     * @param request HttpServletRequest对象
     * @return 是否为POST请求
     */
    public static boolean isPostRequest(HttpServletRequest request) {
        return "POST".equalsIgnoreCase(request.getMethod());
    }

    /**
     * 判断是否为GET请求
     *
     * @param request HttpServletRequest对象
     * @return 是否为GET请求
     */
    public static boolean isGetRequest(HttpServletRequest request) {
        return "GET".equalsIgnoreCase(request.getMethod());
    }

    /**
     * 判断是否为Multipart请求
     *
     * @param request HttpServletRequest对象
     * @return 是否为Multipart请求
     */
    public static boolean isMultipartContent(ServletRequest request) {
        String contentType = request.getContentType();
        return contentType != null && contentType.toLowerCase().startsWith("multipart/");
    }
}
